# -*- coding:utf-8 -*-
"""
# @file name    : lesson-05-Logistic-Regression.py
# @author       : QuZhang
# @date         : 2020-11-28
# @brief        : 逻辑回归训练模型
"""
import torch
import torch.nn as nn
import matplotlib.pylab as plt
import numpy as np
import os
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"


class LR(nn.Module):
    def __init__(self):
        super(LR, self).__init__()
        self.features = nn.Linear(2, 1)  # 全连接层
        self.sigmoid = nn.Sigmoid()  # 激活层

    def forward(self, x):
        x = self.features(x)
        x = self.sigmoid(x)
        return x

if __name__ == "__main__":
    # ----------- step 1/5 生成数据 -------------
    sample_nums = 100
    # mean_value = 1.7
    # mean_value = 1.0
    mean_value = 2.0
    bias = 1
    n_data = torch.ones(sample_nums, 2)  # 维度为(100,2), 值为1的数据
    x0 = torch.normal(mean=mean_value * n_data, std=1) + bias  # 类别0的数据,shape=(100,2)，二维数组的每一行(行，列)都是一个点
    y0 = torch.zeros(sample_nums)                              # 类别0的标签(正确分类)，shape=(100)，表示100个数都是属于这个类别
    x1 = torch.normal(-mean_value*n_data, 1) + bias  # 类别1的数据
    y1 = torch.ones(sample_nums)                     # 类别1的标签
    train_x = torch.cat((x0, x1), dim=0)  # 二维数据在第一维(行)上进行拼接
    train_y = torch.cat((y0, y1), dim=0)  # 一维数据直接拼接

    """
    print("x0[0]: ", x0[0])
    print("x1[0]: ", x1[0])
    print("train_x[0]: ", train_x[0])
    print("train_x[100]: ", train_x[100])
    # print("train_y: ", train_y)
    """

    # --------- step 2/5 选择模型 -------------
    lr_net = LR()  # 实例化逻辑回归模型
    print(lr_net.features)

    # --------- step 3/5 选择损失函数 -------------
    loss_fn = nn.BCELoss()  # 使用二值交叉熵函数创建损失函数对象

    # ---------- step 4/5 选择优化器 --------------
    lr = 0.01
    optimizer = torch.optim.SGD(lr_net.parameters(), lr=lr, momentum=0.9)  # 选择动量

    # ---------- step 5/5 模型训练 ---------------
    for iteration in range(1000):

        # 前向传播
        y_pred = lr_net.forward(train_x)
        # print("y_pred: ", y_pred)
        # print(y_pred.squeeze())

        # 计算损失loss
        loss = loss_fn(y_pred.squeeze(), train_y)
        # 拟合过程：因为前100个数据是属于0分类，所以前100个数剧通过网络之后的预测值y_pred要尽可能<0.5, 后100个尽可能>=0.5

        # 反向传播求梯度,d(loss) / dw , d(loss) / db 保存好
        loss.backward()

        # 更新参数
        optimizer.step()

        # 情空梯度
        optimizer.zero_grad()

        # 绘图
        if iteration % 20 == 0:
            mask = y_pred.ge(0.5).float().squeeze()  # 以0.5为阈值进行分类
            correct = (mask == train_y).sum()  # 计算正确预测的样本个数,结果为一个张量
            acc = correct.item() / train_y.size(0)  # 计算准确率

            plt.scatter(x0.data.numpy()[:, 0], x0.data.numpy()[:, 1], c='r', label="class 0")
            plt.scatter(x1.data.numpy()[:, 0], x1.data.numpy()[:, 1], c='g', label="class 1")

            w0, w1 = lr_net.features.weight[0]  # 张量
            w0, w1 = float(w0.item()), float(w1.item())  # 将张量转为一个数,并转为float型
            plot_b = float(lr_net.features.bias[0].item())
            plot_x = np.arange(-6, 6, 0.1)
            plot_y = (-w0 * plot_x - plot_b) / w1

            plt.xlim(-5, 7)
            plt.ylim(-7, 7)
            plt.plot(plot_x, plot_y)

            plt.text(-5, 5, 'Loss=%.4f' % loss.data.numpy(), fontdict={'size': 20, "color": 'red'})
            plt.title("Iteration: {}\nw0:{:.2f} w1:{:.2f} b: {:.2f} accuracy:{:.2%}".format(iteration, w0, w1, plot_b, acc))
            plt.legend()
            plt.show()
            plt.pause(0.5)

            if acc > 0.99:
                print("final y_pred:\n{}".format(y_pred))
                break